import {
  requestNearbySearch
} from '../../utils/requestUtil.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 地图基础配置
    latitude: 28.129243,
    longitude: 112.894232,
    scale: 15,
    markers: [],

    // 搜索配置
    apiKey: 'DG2BZ-NTRKZ-MEDXK-7NNQB-5W24O-ITBL7',
    searchRadius: 1000, // 单位米
    currentKeyword: '餐饮', // 当前搜索类型
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initMap();
    this.loadNearbyPlaces();
  },

  // 初始化地图位置
  initMap() {
    const {
      latitude,
      longitude,
      searchRadius
    } = this.data
    const circles = [{
      latitude,
      longitude,
      radius: searchRadius,
      color: '#007AFF',
      fillColor: 'rgba(0,122,255,0.05)',
      strokeWidth: 1
    }]
    this.setData({
      circles
    })
  },

  // 加载周边地点
  async loadNearbyPlaces() {
    try {
      const {
        latitude,
        longitude,
        apiKey,
        searchRadius,
        currentKeyword
      } = this.data;
      const boundary = `nearby(${latitude},${longitude},${searchRadius})`;

      // 调用封装的请求方法
      const res = await requestNearbySearch({
        data: {
          key: apiKey,
          boundary,
          keyword: currentKeyword
        }
      });
      console.log(res)
      this.processMarkers(res);
    } catch (error) {
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      console.error('地点加载失败:', error);
    }
  },

  // 处理标记点数据
  processMarkers(places) {
    const markers = places.map((place, index) => ({
      id: index,
      latitude: place.location.lat,
      longitude: place.location.lng,
      title: place.title,
      width: 30,
      height: 30,
      callout: {
        content: `${place.title}\n距离${place._distance.toFixed(0)}米`,
        color: '#333',
        borderRadius: 8,
        padding: 5
      }
    }));
    this.setData({
      markers
    });
  },

  // 标记点击事件
  onMarkerTap(e) {
    const marker = this.data.markers[e.markerId];
    wx.showModal({
      title: '地点详情',
      content: marker.callout.content,
      showCancel: false
    });
  },

  onSearch(e) {
    const currentKeyword = e.detail
    this.setData({
      currentKeyword
    })
    this.initMap();
    this.loadNearbyPlaces();
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})